package com.wxy.library.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

import com.wxy.library.entity.Book;
import com.wxy.library.entity.Borrow;
import com.wxy.library.entity.User;
import com.wxy.library.service.BookService;
import com.wxy.library.service.BorrowService;
import com.wxy.library.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private BookService bookService;

    @Autowired
    private BorrowService borrowService;

    //private Long userId;

    @PostMapping("/register")
    public R<String> register(@RequestBody User user){
//        Long id = user.getUserId();
//        log.info(id.toString());

        userService.save(user);
        return R.success("注册成功");
    }
    @PostMapping("/login")
    public R<User> login(@RequestBody User user){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserId,user.getUserId())
                .eq(User::getPassword,user.getPassword());
        User one = userService.getOne(queryWrapper);
        if(one == null){
            return R.error("账号或密码错误");
        }else {
            one.setPassword("");
            return R.success(one);
        }

    }
    @PostMapping("/session")
    public R<String> getSession(@RequestBody User user,HttpSession session){
        Long userId = user.getUserId();
        session.setAttribute("userId",userId);
        return R.success("ok");
    }
//    @GetMapping
//    public R<String>getsession(HttpSession session){
//        Object userId = session.getAttribute("userId");
//        log.info(userId.toString() + "hello");
//        return null;
//    }
    @PostMapping("/book")
    public R<String> borrow(HttpSession session, @RequestBody Book book){

        Long userId = (Long)session.getAttribute("userId");
        //图书更新条目
        LambdaQueryWrapper<Book> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(Book::getBookId,book.getBookId());
        book = bookService.getOne(updateWrapper);
        LambdaUpdateWrapper<Book> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Book::getBookId,book.getBookId())
                .set(Book::getBookNum,book.getBookNum() - 1);
        bookService.update(wrapper);

        //用户更新条目

        LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(User::getUserId,userId);
        User user = userService.getOne(wrapper1);
        //log.info(user.toString());
        LambdaUpdateWrapper<User> updateWrapper1 = new LambdaUpdateWrapper();
        updateWrapper1.eq(User::getUserId,userId)
                .set(User::getBorrowed,user.getBorrowed() + 1);
        userService.update(updateWrapper1);

        //借书记录更新条目
        Borrow borrow = new Borrow();
        borrow.setUserId(userId);
        borrow.setBookId(book.getBookId());
        borrowService.save(borrow);

        return R.success("借书成功");
    }
    private Boolean veryfy(Book book,List<Book>bookList){
        for(Book book1 : bookList){
            if(book.getBookId().equals(book1.getBookId()))
                return true;
        }
        return false;
    }
    @PostMapping("/return")
    public R<List<JSONObject>>returnBook(@RequestBody Borrow borrow){
        LambdaQueryWrapper<Borrow> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Borrow::getUserId,borrow.getUserId());
        List<Borrow> list = borrowService.list(queryWrapper);
        List<Book> bookList = new ArrayList<>();
        for (Borrow borrow1:list){
            LambdaQueryWrapper<Book>lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Book::getBookId,borrow1.getBookId());
            Book one = bookService.getOne(lambdaQueryWrapper);
            bookList.add(one);
        }

        Set<Book>books = new HashSet<>(bookList);
        List<JSONObject>jsonList = new ArrayList<>();
        for(Book book:books){
            JSONObject bookJson = new JSONObject();
            Integer num = 0;
            for(Book book1 : bookList){
                if(book.getBookId().equals(book1.getBookId()))
                    num++;
            }
            bookJson.put("bookName",book.getBookName());
            bookJson.put("bookAuthor",book.getBookAuthor());
            bookJson.put("num",num);
            bookJson.put("bookId",book.getBookId());
            jsonList.add(bookJson);
        }
        return R.success(jsonList);
    }
    @PostMapping("/return/book")
    public R<String>returnB(@RequestBody Borrow borrow){
        //更新借书的历史
        LambdaQueryWrapper<Borrow> queryWrapper = new LambdaQueryWrapper();

        queryWrapper.eq(Borrow::getBookId,borrow.getBookId());
        Borrow one = borrowService.getOne(queryWrapper,false);
        //log.info(one.toString());
        borrowService.removeById(one.getBorrowId());

        //更新book库存
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Book::getBookId,borrow.getBookId());
        Book one1 = bookService.getOne(wrapper);
        LambdaUpdateWrapper<Book> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(Book::getBookId,one1.getBookId())
                .set(Book::getBookNum,one1.getBookNum() + 1);
        bookService.update(updateWrapper);

        //更新用户
        LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(User::getUserId,borrow.getUserId());
        User user = userService.getOne(wrapper1);
        LambdaUpdateWrapper<User> updateWrapper1 = new LambdaUpdateWrapper();
        updateWrapper1.eq(User::getUserId,user.getUserId())
                .set(User::getBorrowed,user.getBorrowed() - 1);
        userService.update(updateWrapper1);

        return R.success("还书成功!");
    }

    //管理员的操作
    @PostMapping("/edit")
    public R<String>edit(@RequestBody Book book){
        if(book == null)
            return R.error("修改错误!");
        //log.info(book.toString());
        bookService.updateById(book);
        return R.success("修改成功!");
    }

    @PostMapping("/add")
    public R<String>add(@RequestBody Book book){
        if(book == null)
            return R.error("修改错误!");
//        log.info(book.toString());
        bookService.save(book);
        return R.success("插入成功!");
    }

    @PostMapping("/delete")
    public R<String>delete(@RequestBody Book book){
        if(book == null)
            return R.error("删除错误!");
        else {
            bookService.removeById(book.getBookId());
        }
        return R.success("删除成功");
    }
}
